package com.wjk.kylin.id.core.util;

import com.alibaba.fastjson2.JSON;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class HttpUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);
    private static final String APPLICATION_JSON_UTF8 = "application/json;charset=UTF-8";
    private static volatile OkHttpClient httpClient = null;

    /**
     * post请求
     *
     * @return
     */
    public static String doPost(String url, String json) {
        RequestBody requestBody = RequestBody.create(MediaType.parse(APPLICATION_JSON_UTF8), json);

        Request request = new Request.Builder().url(url).post(requestBody).build();
        return doRequest(getHttpClient().newCall(request));
    }

    /**
     * http请求
     *
     * @param call
     * @return
     */
    private static String doRequest(Call call) {
        String result = "";
        Response response = null;
        try {
            response = call.execute();
            if (response.body() == null) {
                throw new NullPointerException("http请求返回response body为空");
            }
            result = response.body().string();
        } catch (Exception e) {
            LOGGER.error("http请求异常: " + JSON.toJSONString(call.request()), e);
        } finally {
            if (null != response && null != response.body()) {
                response.body().close();
            }
        }

        return result;
    }


    /**
     * 初始化 OkHttpClient 根据入参
     *
     * @param connectTimeout
     * @param readTimeout
     * @param writeTimeout
     */
    public static void init(int connectTimeout, int readTimeout, int writeTimeout) {
        if (httpClient == null) {
            synchronized (HttpUtil.class) {
                if (httpClient == null) {
                    httpClient = initClient(connectTimeout, readTimeout, writeTimeout);
                }
            }
        }
    }

    /**
     * 获取 OkHttpClient 默认配置
     *
     * @return
     */
    private static OkHttpClient getHttpClient() {
        if (httpClient == null) {
            synchronized (HttpUtil.class) {
                if (httpClient == null) {
                    httpClient = initClient(60, 60, 60);
                }
            }
        }
        return httpClient;
    }

    /**
     * OkHttpClient 配置
     *
     * @return
     */
    public static OkHttpClient initClient(int connectTimeout, int readTimeout, int writeTimeout) {
        return new OkHttpClient.Builder()
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                .build();
    }

}
